package com.github.wxiaoqi.security.common.config;

import javax.sql.DataSource;

import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import com.ibeetl.starter.BeetlSqlCustomize;
import com.zaxxer.hikari.HikariDataSource;

import cn.hutool.db.Db;
import cn.hutool.db.Session;

@Configuration
@ConditionalOnClass(value = { BeetlSqlDataSource.class })
@ConditionalOnProperty(name = "beetlsql.enabled", havingValue = 
"true", matchIfMissing = true)
public class BeetlSqlDataSourceConfig {

	@Bean(name = "datasource")
	public DataSource datasource(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
		ds.setUsername(env.getProperty("spring.datasource.username"));
		ds.setPassword(env.getProperty("spring.datasource.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		return ds;
	}
	
	@Bean
	public Db hutoolDb(@Qualifier("datasource")DataSource datasource) {
		return new Db(datasource);
	}
	
	@Bean
	public Session hutoolSession(@Qualifier("datasource")DataSource datasource) {
		return new Session(datasource);
	}
	
	@Bean
	public BeetlSqlCustomize beetlSqlCustomize() {
		return new BeetlSqlCustomizeImpl();
	}
}
